package com.qying.protocol.apr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author 秦扬
 * @Date 2022/3/11 17:01
 */
public class Ping {

    public static boolean ping(String ipAddress) throws Exception{
        int timeOut = 3000;
        boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);
        return status;
    }

    public static void ping02(String ipAddress) {
        String line = null;

        try {
            Process process = Runtime.getRuntime().exec("ping " + ipAddress);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
        BufferedReader in = null;
        Runtime runtime = Runtime.getRuntime();

        String pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;

        try {
            System.out.println(pingCommand);
            Process p = runtime.exec(pingCommand);
            if (p == null) {
                return false;
            }

            in = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = null;
            int connectedCount = 0;
            while ((line = in.readLine()) != null) {
                connectedCount += getCheckResult(line);
            }
            return connectedCount == pingTimes;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static int getCheckResult(String line) {

        Pattern pattern= Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while(matcher.find()){
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) throws Exception {
        String ipAddress="127.0.0.1";
        System.out.println(ping(ipAddress));
        ping02(ipAddress);
        System.out.println(ping(ipAddress,5,5000));
    }

}
